package com.ktjy.controller;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.servlet.view.UrlBasedViewResolver;

/** 所有Controller的公共父类
 * @version v1.0
 * @Author JieGe
 * @Create 2024-12-17 - 10:38
 */
public class BaseController {

    // 转发请求
    public String forward(String url) {
        return UrlBasedViewResolver.FORWARD_URL_PREFIX  + url;  // 常量的值为:   forward:
    }
    // 重定向请求
    public String redirect(String url) {
        return UrlBasedViewResolver.REDIRECT_URL_PREFIX + url; // 常量的值为： redirect:
    }

    // 使用RequestContextHolder来获取request请求对象
    public HttpServletRequest request() {
        return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
    }
    // 获取上面的request对象获取session对象
    public HttpSession session() {
        return request().getSession();
    }

    // 161再增加设置数据到request作用域中方法
    public void request(String name, Object obj) {
        request().setAttribute(name, obj);
    }
    // 从request作用域中通过key取出对应的值
    public <T> T request(String name) {
        return (T)request().getAttribute(name);
    }

    // 保存数据到session作用域中
    public void session(String name, Object obj) {
        session().setAttribute(name, obj);
    }
    // 从request作用域中通过key取出对应的值
    public <T> T session(String name) {
        return (T)session().getAttribute(name);
    }
    public void removeSession(String name) {
        session().removeAttribute(name);
    }
}
